<?php

include_once 'api/resume.php';

class Mail {
	
	static $from;
	static $to;
	static $subject;
	static $message;
	
	static function send($message, $subject = null) {
		
		if ($subject === null)
			$subject = self::$subject;
		
		$headers = 'From: ' . self::$from . "\r\n" . 'Content-Type:text/html; charset=UTF-8' . "\r\n";
		
		mail ( self::$to, $subject, $message, $headers );
	
	}
	
	static function configure($configurationFile = null) {
		
		if ($configurationFile === null)
			return false;
		
		$strJson = json_decode ( file_get_contents ( $configurationFile ) );
		$strJson = $strJson->default;
		
		self::$from = $strJson->from;
		self::$to = $strJson->to;
		self::$subject = $strJson->subject;
		self::$message = $strJson->message;
	
	}
	
	static function setFrom($from = null) {
		self::$from = $from;
	}
	static function setTo($to = null) {
		self::$to = $to;
	}
	static function setSubject($subject = null) {
		self::$subject = $subject;
	}
	static function setMessage($message = null) {
		self::$message = $message;
	}
	
	static function spamcheck($field) {
		//filter_var() sanitizes the e-mail
		//address using FILTER_SANITIZE_EMAIL
		$field = filter_var ( $field, FILTER_SANITIZE_EMAIL );
		
		//filter_var() validates the e-mail
		//address using FILTER_VALIDATE_EMAIL
		if (filter_var ( $field, FILTER_VALIDATE_EMAIL )) {
			return true;
		} else {
			return false;
		}
	}
}

if (isset ( $_REQUEST ['t'] ) === false)
	exit ( '{"r": false, "e": 1}' );

if (mail::spamcheck ( $_REQUEST ['t'] ) == false) {
	exit ( '{"r": false, "e": 2}' );
}

Mail::configure ( 'config/mail.config.json' );
Mail::setTo ( $_REQUEST ['t'] );
Mail::send ( resume () );

file_put_contents ( 'log/send.log', date ( "Y-m-d H:i:s > " ) . $_REQUEST ['t'] . "\r\n", FILE_APPEND );

echo '{"r": true}';
